<template>
  <div class="hello">
    <mt-header title="图书馆自修室预约"> </mt-header>
    <p style="font-size: 1rem; margin: 0; color: #646363; margin: 0.5rem">
      <i class="fa fa-map-marker"></i>&nbsp;<small
        >一楼自修室(周一至周日09:00~22:00)</small
      >
    </p>
    <div>
      <!--有空闲座位时-->
      <p v-show="seatStatusFlag">
        <a href="javascript:;"
          ><small>剩余座位{{ remainNum }}个，点击下方选择座位</small></a
        >
      </p>
      <!--排队时-->
      <p v-show="queueStatusFlag">
        <small
          >您的座位号是{{ seatNumber }}，入座剩余时间：<a href="javascript:;"
            >{{ minutes }}分{{ seconds }}秒</a
          ></small
        >
      </p>
      <!--没有空闲座位时-->
      <p v-show="noEmptySeatFlag">
        <mt-button
          type="primary"
          v-show="queueButtonFlag"
          size="small"
          @click.native="startQueue"
          >开始排队</mt-button
        >
        <span v-show="queueNumberFlag"
          >您排第&nbsp;{{ queueNumber }}&nbsp;位</span
        >
      </p>
      <!--入座后-->
      <p v-show="seatLeaveFlag">
        您的座位&nbsp;{{ seatNumber }}&nbsp;&nbsp;&nbsp;
        <mt-button type="primary" size="small" @click.native="confirmLeave"
          >确认离座</mt-button
        >
      </p>
    </div>
    <div class="current-seat text-left">
      <p>
        <i class="remain"></i><b>&nbsp;未座：{{ remainNum }}</b
        >&nbsp;&nbsp;<i class="no-remain"></i><b>&nbsp;已座</b>
        <span class="pull-right"
          ><small>扫一扫入座&nbsp;</small
          ><span class="fa fa-qrcode fa-lg" @click="scanQRcode"></span
        ></span>
      </p>
    </div>
    <p>
      <span class="enterance">入口</span>
    </p>
    <div class="seat-detail">
      <ul class="rows clearfix">
        <li
          v-for="(val, key, index) in callbackData"
          :data-index="key"
          :key="index"
          :class="{
            occupied: val,
            mine: key == id && id,
            seated: seatedFlag && key == id && id,
          }"
          @click="orderSeat(key, val)"
        >
          {{ key }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
//MessageBox不是全局组件，故需要单独引入
import { MessageBox } from 'mint-ui'
export default {
  name: 'library',
  data() {
    return {
      queueNumber: '', //当前排队序号
      seatNumber: '', //当前座位号
      remainNum: '', //剩余座位
      minutes: 5,
      seconds: 0,
      seatStatusFlag: true, //空闲座位状态
      queueStatusFlag: false, //排队状态
      noEmptySeatFlag: false, //满座状态
      seatLeaveFlag: false, //入座状态
      queueNumberFlag: false, //开始排队后显示当前位置标识
      queueButtonFlag: true, //"开始排队"按钮标识
      seatedFlag: false, //已入座状态
      callbackData: '', //列表数据
      mineFlag: false, //占座标识
      remainMinutes: 0.5, //默认配置倒计时5分钟
      remainSeconds: this.remainMinutes * 60,
      timer: '', //定时器
      id: '', //当前座位索引
      mineId: '',
      userId: 'zhangqianfeng',
      timer: '',
      dialogVisible: false,
    }
  },
  mounted() {
    //初始化执行函数，故mounted不是一个对象而是函数
    console.log(666)
    this.getList()
  },
  methods: {
    startQueue() {
      console.log('开始排队')
      MessageBox.confirm('确认开始排队？?').then(
        () => {
          //查询当前排队信息
          this.$http.get('/static/api/queue.json').then((res) => {
            if (res.body.success) {
              //发送用户信息开始排队
              this.$http
                .get('/static/api/postData.json', { userId: this.userId })
                .then((result) => {
                  if (result.body.success) {
                    MessageBox.alert('排队成功！').then(() => {
                      this.queueNumberFlag = true
                      this.queueButtonFlag = false
                      //当前排队位置 = 总排队人数+1
                      this.queueNumber = res.body.queueNumberTotal * 1 + 1
                    })
                  } else {
                    MessageBox.alert('排队出错，请稍后重试！')
                    return false
                  }
                })
            } else {
              MessageBox.alert('查询排队信息出错，请稍后重试！')
              return false
            }
          })
        },
        () => {
          console.log('取消排队')
        }
      )
    },
    //点击预约位置
    orderSeat(key, val) {
      console.log('key==' + key + ',val==' + val)
      if (!this.seatedFlag) {
        if (val) {
          MessageBox.alert('当前座位已被占用，请选择未占用的位置！')
          return false
        } else if (this.id == key) {
          MessageBox.alert('您已经占过该位置，请勿重复占用！')
          return false
        } else {
          //换座位，重新计时
          if (this.id) {
            //已占据位置标识
            let nextId = key
            MessageBox.confirm(
              '当前已占座位' + this.id + ',是否切换到新的座位' + nextId + '？'
            ).then(
              () => {
                this.id = key
                MessageBox.alert('已成功切换到新位置' + nextId + '号！')

                this.seatNumber = key
                this.seatStatusFlag = false
                this.queueStatusFlag = true
                this.noEmptySeatFlag = false
                this.seatLeaveFlag = false

                clearInterval(this.timer)
                this.remainSeconds = this.remainMinutes * 60
                this.countDown(this.remainSeconds)
                this.timer = setInterval(() => {
                  this.countDown(this.remainSeconds)
                }, 1000)
              },
              () => {
                console.log('取消切换位置')
              }
            )
          } else {
            //未占据任何位置
            MessageBox.confirm('确认预约当前位置？').then(
              () => {
                this.id = key
                this.loadAjax(() => {
                  MessageBox.alert('占座成功,将为您保留五分钟！')
                  this.remainNum = this.remainNum - 1
                  this.seatNumber = key
                  this.seatStatusFlag = false
                  this.queueStatusFlag = true
                  this.noEmptySeatFlag = false
                  this.seatLeaveFlag = false

                  clearInterval(this.timer)
                  this.remainSeconds = this.remainMinutes * 60
                  this.countDown(this.remainSeconds)
                  this.timer = setInterval(() => {
                    this.countDown(this.remainSeconds)
                  }, 1000)
                })
              },
              () => {
                console.log('取消预约')
              }
            )
          }
        }
      } else {
        MessageBox.alert('您当前已入座，请勿重复占座！')
        return false
      }
    },
    confirmLeave() {
      console.log('确认离开座位')
      MessageBox.confirm('确认离开此位置？').then(
        () => {
          this.$http.get('/static/api/postData.json', { id: this.id }).then(
            () => {
              MessageBox.alert('已离开当前位置！')
              this.id = ''
              this.remainNum += 1
              this.seatedFlag = false

              this.seatStatusFlag = true
              this.queueStatusFlag = false
              this.noEmptySeatFlag = false
              this.seatLeaveFlag = false
              this.getList()
            },
            () => {}
          )
        },
        () => {
          console.log('取消离开位置')
        }
      )
    },
    //扫描二维码入座
    scanQRcode() {
      console.log('扫描二维码入座')
      if (this.seatedFlag) {
        MessageBox.alert('当前已入座')
      } else {
        MessageBox.prompt('请输入座位号')
          .then(({ value, action }) => {
            console.log(value, action)
            if (this.id == value) {
              this.$http.get('/static/api/postData.json', { id: this.id }).then(
                (res) => {
                  if (res.body.success) {
                    clearInterval(this.timer)
                    MessageBox.alert('入座成功！')
                    this.seatedFlag = true
                    this.seatStatusFlag = false
                    this.queueStatusFlag = false
                    this.noEmptySeatFlag = false
                    this.seatLeaveFlag = true
                  }
                },
                () => {}
              )
            } else {
              MessageBox.alert('未查询到相关预约信息，请核实信息！')
              return false
            }
          })
          .catch((err) => {
            console.log(err)
          })
      }
    },
    //加载座位列表
    getList() {
      this.$http
        .get('/static/api/index.json', { id: this.id })
        .then(function (res) {
          this.callbackData = res.body.data
          this.remainNum = res.body.remain
          if (this.remainNum == 0) {
            this.seatStatusFlag = false
            this.noEmptySeatFlag = true
          }
        }),
        function (res) {}
    },
    loadAjax(callback) {
      this.$http
        .get('/static/api/postData.json', { id: this.id, userId: this.userId })
        .then(
          (res) => {
            if (res.body.success) {
              if (callback) {
                callback()
              }
            } else {
              MessageBox.alert('手慢了，座位被别人占用了！')
            }
          },
          () => {}
        )
    },
    //倒计时
    countDown(sec) {
      let timeArr = []
      timeArr[0] = Math.floor(sec / 60)
      timeArr[1] = sec % 60
      this.minutes = timeArr[0]
      this.seconds = timeArr[1]
      if (this.remainSeconds == 0) {
        clearInterval(this.timer)
        this.remainNum += 1
        this.seatStatusFlag = true
        this.queueStatusFlag = false
        this.noEmptySeatFlag = false
        this.seatLeaveFlag = false
        this.id = ''
      }
      this.remainSeconds--
    },
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1,
h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0;
}

a {
  color: #0894ec;
  text-decoration: none;
}

* {
  touch-action: none;
}
p {
  margin: 0.5rem;
}
.clearfix:after,
.clearfix:before {
  width: 0;
  height: 0;
  content: '';
  display: block;
  clear: both;
}
.text-left {
  text-align: left;
}
.remain {
  display: inline-block;
  width: 1.5rem;
  height: 1.25rem;
  background: #67ed84;
}
.no-remain {
  display: inline-block;
  width: 1.5rem;
  height: 1.25rem;
  background: #f9848e;
}
.occupied {
  background: #f9848e !important;
}
.mine {
  background: #9ca6f4 !important;
}
.seated {
  background: orange !important;
}

.current-seat > p {
  height: 1.25rem;
  line-height: 1.25rem;
}
.current-seat b {
  display: inline-block;
  line-height: 1.25rem;
  height: 1.25rem;
  font-style: normal;
  font-weight: normal;
  vertical-align: top;
}
.enterance {
  width: 7rem;
  height: 1.5rem;
  border: 1px solid #e1e1e1;
  display: inline-block;
  line-height: 1.5rem;
}
.seat-detail {
  margin: 0.5rem;
}
.seat-detail .rows {
  margin: 0;
  padding: 0;
  width: 100%;
}
.seat-detail li {
  float: left;
  width: 10%;
  height: 1.2rem;
  line-height: 1.2rem;
  margin-right: 0.7%;
  margin-bottom: 0.2rem;
  background: #67ed84;
  text-align: center;
}
.seat-detail li:nth-of-type(18n) {
  margin-bottom: 0.4rem;
}
.seat-detail li:nth-of-type(9n + 3) {
  margin-right: 2.9%;
}
.seat-detail li:nth-of-type(9n + 6) {
  margin-right: 2.9%;
}
.seat-detail li:nth-of-type(9n) {
  margin-right: 0;
}
</style>